package org.ftc.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.ftc.dao.UsersDao;
import org.ftc.domain.RoleAuth;
import org.ftc.domain.Users;
import org.ftc.form.UsersForm;
import org.ftc.security.User;
import org.ftc.util.ServlerUtil;
import org.ftc.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class UsersService {

	@Autowired
	UsersDao usersDao;
	@Autowired
	RoleAuthService roleAuthService;
	@Autowired
	ServlerUtil servlerUtil;

	public Users load(String id) {
		return usersDao.load(id);
	}

	public Users get(String id) {
		return usersDao.get(id);
	}

	public synchronized boolean save(Users entity) {
		Authentication userDetails = SecurityContextHolder.getContext().getAuthentication();
		if (userDetails != null)
			entity.setCreationUser(userDetails.getName());
		entity.setCreationDate(new Date());
		return usersDao.save(entity);
	}

	public synchronized boolean saveOrUpdate(Users entity) {
		return usersDao.saveOrUpdate(entity);
	}

	public synchronized boolean update(Users entity) {
		try {
			entity.setModifyDate(new Date());
			entity.setModifyUser(SecurityContextHolder.getContext().getAuthentication().getName());
//			servlerUtil.stprogram(entity);
			return usersDao.update(entity);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public synchronized boolean delete(Users entity) {
		return usersDao.delete(entity);
	}

	public synchronized boolean delete(String id) {
		return usersDao.delete(id);
	}

	public List<Users> findPage(int offset, int pageSize) {
		return usersDao.findPage(offset, pageSize);
	}

	public List<Users> findAll() {
		return usersDao.findAll();
	}

	public long countAll() {
		return usersDao.countAll();
	}

	public List<Users> findPage(UsersForm form, int offset, int pageSize) {
		return usersDao.findPage(form, offset, pageSize);
	}

	public long count(UsersForm form) {
		return usersDao.count(form);
	}

	public Users findUserByIdEmail(String userName, String email) {
		return usersDao.findUserByIdEmail(userName, email);
	}

	public User loginUserName(String userName) {
		Users users = usersDao.loginUserName(userName);
		if (users == null)
			return null;
		// 功能權限
		List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();
		authSet.add(new SimpleGrantedAuthority("HOME"));
		if (users.getRole() != null && users.getRole().length() > 0) {
			RoleAuth roleAuth = roleAuthService.get(users.getRole());
			if (roleAuth != null) {
				for (String auth : roleAuth.getAuths().split(",")) {
					authSet.add(new SimpleGrantedAuthority(auth));
				}
			}
		}
		User user = new User(users.getUserName(), users.getPassword(), users.getStatus()==1?true:false, users.getRole(), authSet);
		return user;
	}

	public Users findByUserName(String userName) {
		return usersDao.findByUserName(userName);
	}
	
	public List<Users> findType(String type) {
		return usersDao.findType(type);
	}
	
	public List<Users> findUser(UsersForm userForm) {
		return usersDao.findUser(userForm);
	}

	public Users findByEmailType(String email, String type) {
		return usersDao.findByEmailType(email, type);
	}

	public Users[] findByRole(String role) {
		List<Users> list = usersDao.findByRole(role);
		return list.toArray(new Users[0]);
	}

	public Users[] findByCodeOrgan(String codeOrgan) {
		List<Users> list = usersDao.findByCodeOrgan(codeOrgan);
		return list.toArray(new Users[0]);
	}

	public Users securityByUser() {
		Authentication userDetails = SecurityContextHolder.getContext().getAuthentication();
		if (userDetails != null)
			return this.findByUserName(userDetails.getName());
		return null;
	}

	public boolean hasRole(String role) {
		boolean hasRole = false;
		Users userDetails = securityByUser();
		if (userDetails != null) {
			RoleAuth roleAuth = roleAuthService.get(userDetails.getRole());
			if (roleAuth != null) {
				for (String auth : roleAuth.getAuths().split(",")) {
					if (auth.equals(role)) {
						return true;
					}
				}
			}
		}
		return hasRole;
	}
	
	public boolean hasRole(String role,Users userDetails) {
		boolean hasRole = false;
		if (userDetails != null) {
			RoleAuth roleAuth = roleAuthService.get(userDetails.getRole());
			if (roleAuth != null) {
				for (String auth : roleAuth.getAuths().split(",")) {
					if (auth.equals(role)) {
						return true;
					}
				}
			}
		}
		return hasRole;
	} 
	
	public List<HashMap<String,String>> findByName(UsersForm form) {
		List<Users> list = usersDao.findByName(form);
		List<HashMap<String,String>> data = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(list)){
			for(Users users:list){
				HashMap<String,String> map = new HashMap<>();
				map.put("id", users.getUsersSeq());
				map.put("name", users.getName());
				data.add(map);
			}
		}
		return data;
	}
	
	public String token(String usersSeq){
		if(StringUtils.isNotBlank(usersSeq)){
			List<HashMap<String,String>> data = new ArrayList<>();
			for(String id : usersSeq.split(",") ){//措施的主協辦機關排序是很重要的 順序問題
				Users users = usersDao.get(id);
				if(null!=users){
					HashMap<String,String> map = new HashMap<>();
					map.put("id", users.getUsersSeq());
					map.put("name", users.getName());
					data.add(map);
				}
			}
			return Util.listToJson(data)==null?"[]":Util.listToJson(data);
		}
		return "[]";
	}
	
	public String transferName(String id) {
		String name = "";
		if(StringUtils.isNotBlank(id)){
			for(final String userCode : id.split(",") ){
				Users users = this.get(userCode);
				if(userCode==null){
					 continue;
				}
				name = name.concat( users.getName()+"," );
			}
			name = StringUtils.substringBeforeLast(name, ",");
		}
		return name;
	}
	
	public List<HashMap<String,String>> findUsers(String id) {
		List<HashMap<String,String>> data = new ArrayList<>();
		if(StringUtils.isNotBlank(id)){
			for(final String userCode : id.split(",") ){
				Users users = this.get(userCode);
				if(userCode==null){
					 continue;
				}
				HashMap<String,String> map = new HashMap<>();
				map.put("id", users.getUsersSeq());
				map.put("name", users.getName());
				map.put("tel", users.getTelephone());
				map.put("email", users.getEmail());
				data.add(map);
			}
		}
		return data;
	}
	
	public List<Users> findRecorder(){
		return usersDao.findRecorder();
	}

	public enum TypeCode {
		USERS("用戶");
		private final String name;

		TypeCode(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}
	}
}
